package com.reflex;

import com.excel.excelUtil.dto.LawFirmInfo;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhuangqi
 * @@date 2017/3/23.
 */
public class ReflexTest3 {
    public static void main(String[] args) {
//        String test = "lawFirmName";
//        String test2 = test.substring(0,1).toUpperCase() + test.substring(1);
//        System.out.println(test);
//        System.out.println(test2);
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("lawFirmName","庄奇测试律所");
        map.put("sum",1);
        try {
            LawFirmInfo info = map2Bean(LawFirmInfo.class,map);
            System.out.println(info.getLawFirmName());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }

    private static <T> T map2Bean(Class clazz,Map map) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
        T bean = (T) clazz.newInstance();
        Method[] methods = clazz.getMethods();
        for (Method method : methods){
            if (method.getName().startsWith("set")){
                String methodName = method.getName().substring(3);
                String fileName = methodName.substring(0,1).toLowerCase()+methodName.substring(1);
                if (map.containsKey(fileName)){
                    Class[] parameterTypes = method.getParameterTypes();
                    if (parameterTypes.length!=1){
                        throw new RuntimeException("EXCEL BEAN SET 方法参数只能有一个");
                    }
                    for (Class type:parameterTypes){
                        if (!type.getName().equals(String.class.getName())){
                            throw new RuntimeException("EXCEL BEAN SET 方法参数必须为String类型");
                        }
                    }
                    Method objectSet = clazz.getDeclaredMethod(method.getName(),String.class);
                    objectSet.invoke(bean,map.get(fileName));
                }
            }
        }
        return bean;
    }
}
